#!/opt/bin/bash

LOG_FILE="/tmp/rsync.log" 
TMP_LOG="/tmp/rsync.tmp" 
## -avurz : Archive(a) Verbose(v) Update(u) Recursive(r) Compress(z)
##RSYNC_OPT="-avrhzO --delete --stats --progress --exclude=\"@eaDir\" --log-file=$LOG_FILE"
REMOTE_HOST="ks397022.ip-192-95-27.net"
MAIL_SCRIPT="/opt/bin/nail"
ROOT_TARGET_BCK=/home/data/owncloud/
RESULT=0

START_DATE=""
END_DATE=""

NB_FILES=""
NB_SIZE=""

## ####################################### ##
Log()
{
	echo "$1<br/>" >> $LOG_FILE
}

LogTitle()
{
	echo "$1" >> $LOG_FILE
}

## ####################################### ##
BlankLine()
{
	echo "<br/>" >> $LOG_FILE
}

## ####################################### ##
LineSeparator()
{
	echo "<hr/>" >> $LOG_FILE
}

## ####################################### ##
CleanLog() 
{
	rm -f $TMP_LOG
	rm -f $1
	echo "" > $1
}

## ####################################### ##
InitLog() 
{
	LOG_FILE=`echo "$1"`
	export LOG_FILE
	TMP_LOG=`echo "$1.tmp"`
	export TMP_LOG

	CleanLog $LOG_FILE

	DATE=`date +%d-%b-%Y`
	TIME=`date +%H:%M:%S`
	TIMESTAMP=`date +%d%b%Y`
	TIMESTAMP2=`date +%H%M%S`
	START_DATE=`echo "$DATE - $TIME"`
	
	LineSeparator
	LogTitle "<h2>******* Starting backup *********</h2>"
	Log "<b>$DATE - $TIME</b>"
	LineSeparator
}

## ####################################### ##
CountNbFilesTransferred()
{
	NB_FILES=`grep "Number of files transferred " $LOG_FILE | grep -v '\['`
	NB_SIZE=`grep "Total transferred file size " $LOG_FILE | grep -v '\['`
	
	Log "<b>$NB_FILES</b>"
	Log "<b>$NB_SIZE</b>"
}

## ####################################### ##
CloseLog() 
{
	sed -e 's/$/<br\/>/' $TMP_LOG >> $LOG_FILE

	DATE=`date +%d-%b-%Y`
	TIME=`date +%H:%M:%S`
	END_DATE=`echo "$DATE - $TIME"`
	
	BlankLine
	LineSeparator
	Log "<b>Start : $START_DATE</b>"
	CountNbFilesTransferred	
	Log "<b>End : $END_DATE</b>"
	LogTitle "<h2>******* Backup complete *********</h2>"
	LineSeparator
}

## ####################################### ##
LogResult() 
{
	RES=$1
	let RESULT+=$RES
	if (($RES==0))
	then
		Log "<b><font color=green> -> OK</font></b>"
	else
		Log "<b><font color=red>  -> NOK</font></b>"
		Log "<b><font color=red> Error : $1</font></b>"
	fi
}

## ####################################### ##
LogStep() 
{
	TITLE=$1
	ARGS=$2
	if [ -z "$ARGS" ]
	then
		Log "<h3>* $1 ($ARGS) : </h3>"
	else
		Log "<h3>* $1 : </h3>"
	fi
}


## ####################################### ##
## Sync remoted folder with local backup folder
Sync() 
{
	SRC_DIR="$1"
	DST_DIR="$2"
	SSH_USR="$3"

	LogStep "Syncing folders : local => remote using $SSH_USR"
	echo "<li>Rsync Options : <i>--delete -avrhzO --stats --progress</i></li>" >> $LOG_FILE
	echo "<li>SSH User : <i>$SSH_USR</i></li>" >> $LOG_FILE
	echo "<li>Source folder : <i>$SRC_DIR</i></li>" >> $LOG_FILE
	echo "<li>Destination Folder : <i>$DST_DIR</i></li>" >> $LOG_FILE

	rsync -e "ssh -i $SSH_KEY_FILE -l $SSH_USR" --delete -avrhzO --stats --progress --exclude="@eaDir" $SRC_DIR $DST_DIR --log-file=$TMP_LOG 

	LogResult $?
}

